package com.jiuzhou.common.log.aspect;

import com.jiuzhou.common.core.utils.JsonUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 操作日志记录处理
 *
 * @author sasac
 */
@Aspect
@Component
public class BusinessLogAspect {
    private static final Logger log = LoggerFactory.getLogger(BusinessLogAspect.class);

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) || @annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping) || @annotation(org.springframework.web.bind.annotation.DeleteMapping) ")
    public void logPointCut() {
    }


    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 过滤非请求
        if (requestAttributes == null) {
            return null;
        }
        HttpServletRequest request = requestAttributes.getRequest();

        // 类名
        String controllerName = joinPoint.getTarget().getClass().getName();
        // 方法名称
        String methodName = joinPoint.getSignature().getName();

        long beginTime = System.currentTimeMillis();
        // 响应数据
        Object proceed = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        // 请求数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        String requestData = JsonUtils.obj2String(parameterMap);
        String responseData = JsonUtils.obj2String(proceed);
        long time = endTime - beginTime;
        log.info("{}-{}.{}()-{}ms-{}-{}", request.getRequestURI(), controllerName, methodName, time, requestData, responseData);
//        log.info("请求路径：{}-请求方法：{}.{}()-请求参数：{}-响应结果：{}-耗时：{}ms", request.getRequestURI(), controllerName, methodName, requestData, responseData, time);

        return proceed;
    }


}
